package app;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.TreeSet;
import org.commons.Utils;

import app.structure.Graph;

public class DecoyPlacer {

	private Graph graph;

	public DecoyPlacer(Graph graph) {
		this.graph = graph;

	}

	public void placeDecoys(String decoyLink, int howMany) {
		TreeMap<Integer, TreeSet<Integer>> degreeMap = new TreeMap<Integer, TreeSet<Integer>>();

		Iterator<Integer> iToCheck = graph.getHashPathMap().keySet().iterator();
		while(iToCheck.hasNext()) {
			Integer nodeHash = iToCheck.next();
			int nodeDegree = 0;
			TreeSet<Integer> tmp = graph.getHashGraph().get(nodeHash);
			if(tmp != null)
				nodeDegree = tmp.size();

			TreeSet<Integer> degreeList = degreeMap.get(nodeDegree);
			if (degreeList == null) {
				degreeList = new TreeSet<Integer>();
				degreeMap.put(nodeDegree, degreeList);
			}
			degreeList.add(nodeHash);

		}

		Iterator<Integer> iDegree = degreeMap.navigableKeySet().descendingIterator();
		ArrayList<Integer> hashesToPlaceDecoys = new ArrayList<Integer>();
		while(iDegree.hasNext() && hashesToPlaceDecoys.size() < howMany) {
			TreeSet<Integer> degreeList = degreeMap.get(iDegree.next());
			Iterator<Integer> iToPlace = degreeList.iterator();
			while(iToPlace.hasNext() && hashesToPlaceDecoys.size() < howMany) {
				hashesToPlaceDecoys.add(iToPlace.next());
			}
		}

		System.out.println(degreeMap);
		System.out.println(hashesToPlaceDecoys);	

		//hashesToPlaceDecoys contiene howMany hash delle pagine con grado maggiore (in cui vanno messi i decoy)
		//per avere il percorso di un decoy basta che fai
		//graph.getAbsolutePath(hashesToPlaceDecoys.get(0));
		for (int i=0; i<hashesToPlaceDecoys.size(); i++) {
			int pageHash = hashesToPlaceDecoys.get(i);
			String page = graph.getAbsolutePath(hashesToPlaceDecoys.get(i));
			int decoyPerPage = graph.getHashGraph().get(pageHash).size();
			System.out.println(page + " " + decoyPerPage);
			Utils.addDecoyLinks(decoyLink, page, decoyPerPage);
		}
	}

	public void removeDecoys(String decoyLink) {
		Iterator<Integer> iToCheck = graph.getHashPathMap().keySet().iterator();
		while(iToCheck.hasNext()) {
			String page = graph.getAbsolutePath(iToCheck.next());
			Utils.removeAllDecoyLinks(decoyLink, page);
		}
	}
}
